var MeasureToolCheckTableInit = function () {
    var oTableInit = {};
    //初始化Table
    oTableInit.Init = function () {
        $('#checkRecordTable').bootstrapTable({
            url: ctx + '/measureTool/measureToolCheckRecord/getMeasureToolCheckRecordList/get.mvc',         //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
//            toolbar: '#toolbar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            paginationLoop: false,
            sortable: true,                     //是否启用排序
            sortOrder: "asc",                   //排序方式
            queryParams: oTableInit.queryParams,//传递参数（*）
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            strictSearch: true,
            showColumns: false,                  //是否显示所有的列
            showRefresh: false,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            height: 500,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "pkId",                     //每一行的唯一标识，一般为主键列
            showToggle: false,                    //是否显示详细视图和列表视图的切换按钮
            cardView: false,                    //是否显示详细视图
            detailView: false,                   //是否显示父子表
            singleSelect: false,                    //禁止多选
            checkboxHeader: true,                 //列头取消多选
            columns: [
               // {
                 //   radio: true,
                 //   align: 'center',
                //    valign: 'middle'
               // },
                {
                    title: '序号',
                    align: 'center',
                    valign: 'middle',
                    formatter: function (value, row, index) {
                        var options = $('#checkRecordTable').bootstrapTable('getOptions');
                        return options.pageSize * (options.pageNumber - 1) + index + 1;
                    }
                }, {
                    field: 'measureToolCode',
                    title: '计量器具编码',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'
                }, {
                    field: 'measureToolName',
                    title: '计量器具名称',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'
                }, {
                    field: 'equipCode',
                    title: '设备编码',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'
                }, {
                    field: 'equipName',
                    title: '设备名称',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'
                }, {
                    field: 'areaName',
                    title: '区域',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'

                }, {
                    field: 'department',
                    title: '部门',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'

                }, {
                    field: 'checkDate',
                    title: '校验日期',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'

                }, {
                    field: '',
                    title: '操作',
                    sortable: false,
                    align: 'center',
                    valign: 'middle',
                    formatter: function (value, row, index) {
                        return "<a href='javascript:;' class='click_btn detail' data-pkid='" + row.pkId + "'>查看</a>";
                    }

                }, {
                    field: 'pkId',
                    title: 'pkId',
                    visible: false
                }]

        });
    };
    //得到查询的参数
    oTableInit.queryParams = function (params) {
        return {   // 这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            size: params.limit,   // 页面大小
            num: (params.offset/params.limit) + 1,  // 页码
            sort: params.sort,
            order: params.order,
            measureToolCode: $("#measureToolCodeQuerySelect2").find("option:selected").text(),
            measureToolName: $("#measureToolName").val(),
            equipCode: $("#equipCode").find("option:selected").text(),
            checkDateStart: $("#checkDateStart").val(),
            checkDateEnd: $("#checkDateEnd").val()
        }
    };
    return oTableInit;
};

jQuery(document).ready(function () {
    //1.初始化Table
    var oTable = new MeasureToolCheckTableInit();
    oTable.Init();
    //初始化页面
    measureToolCheckInit.init();
});


var measureToolCheckInit = function () {
    return {
        init: function () {
            measureToolCheckInit._modalHidden();
            measureToolCheckInit._initMeasureToolCodeQuerySelect2();
            measureToolCheckInit._initEquipCodeSelect2();
            measureToolCheckInit._initDateControl();
            measureToolCheckInit._check();
            measureToolCheckInit._query();
            measureToolCheckInit._keyQuery();
            measureToolCheckInit._refresh();
            measureToolCheckInit._reset();
        },
        //条件查询
        _query: function () {
            $("#queryRecord").on("click", function () {
                $('#checkRecordTable').bootstrapTable('refreshOptions', {
                    pageNumber: 1
                });
            });
        },
        //按键查询
        _keyQuery: function () {
            $(".tool-check-search").keypress(function (e) {
                if (e.which === 13) {
                    $("#queryRecord").trigger("click");
                }
            });
        },
        //重置查询
        _reset: function () {
            $(".reset").on("click", function () {
                $(".clearfix input").val("");
                $("#measureToolCodeQuerySelect2").val(null).trigger("change");
                $("#equipCode").val(null).trigger("change");
            });

        },
        _refresh: function () {
            //刷新
            $("#refreshTable").on("click", function () {
                $('#checkRecordTable').bootstrapTable('refresh');
            });
        },
        _initDateControl: function () {
            $('.form-datetime').datetimepicker({
                format: 'yyyy-mm-dd hh:ii:ss',
                language: 'zh-CN',
                autoclose: true,
                pickerPosition: "bottom-left",
                //endDate : new Date(),
                forceParse: true
            }).on('hide', function (event) {
                event.preventDefault();
                event.stopPropagation();
            });
            $('.form-datetime-day').datetimepicker({
                format: 'yyyy-mm-dd',
                minView: 2,
                autoclose: true,
                language: 'zh-CN',
                pickerPosition: "bottom-left",
                //endDate : new Date(),
                forceParse: true
            }).on('hide', function (event) {
                event.preventDefault();
                event.stopPropagation();
            });
        },
        _initEquipCodeSelect2 : function () {
            $('#equipCode').select2({
                ajax: {
                    url: ctx + '/measureTool/measureToolInfo/getEquipmentList/get.mvc',
                    dataType: 'json',
                    data: function (params) {
                        // Query parameters will be ?search=[term]&page=[page]
                        return {
                            search: params.term,
                            page: params.page || 1,
                            size: 10
                        };
                    },
                    processResults: function (response) {
                        // Tranforms the top-level key of the response object from 'items' to 'results'
                        var test = [];
                        if (response.data) {
                            var _data = response.data;
                            for (var int = 0; int < _data.length; int++) {
                                var obj = {};
                                obj.id = _data[int].pkId;
                                obj.text = _data[int].equipCode;
                                test.push(obj);
                            }
                        }
                        return {
                            results: test
                        };
                    },
                    // Additional AJAX parameters go here; see the end of this chapter for the full code of this example
                    cache: true

                },
                placeholder: '请选择',
                language: "zh-CN",
                escapeMarkup: function (markup) {
                    return markup;
                }, // let our custom formatter work
                minimumInputLength: 0
            });
        },
        //新增
        _check: function () {
            $("#checkRecordTable").on('click', 'a.detail', function (e) {
                e.preventDefault();
                $('#myModal .modal-title').html("计量器具校验详情");
                var pkId = $(this).data("pkid");
                console.log(pkId);
                $.ajax({
                    url: ctx + "/measureTool/measureToolCheckRecord/getMeasureToolCheckResult/get.mvc",
                    type: "post",
                    dataType: "json",
                    data: {
                        pkId: pkId.toString()
                    },
                    success: function (response) {
                        //debugger
                        if (response.result === true) {
                            if(response.data) {
                                var _data = response.data;
                                $("#measureToolCheckForm").find("input[name=measureToolCode]").val(_data.measureToolCode);
                                $("#measureToolCheckForm").find("input[name=department]").val(_data.department);
                                $("#measureToolCheckForm").find("input[name=equipCode]").val(_data.equipCode);
                                $("#measureToolCheckForm").find("input[name=measureRange]").val(_data.measureRange);
                                $("#measureToolCheckForm").find("input[name=detectionSite]").val(_data.detectionSite);
                                $("#measureToolCheckForm").find("input[name=humidity]").val(_data.humidity);
                                $("#measureToolCheckForm").find("input[name=standardCode]").val(_data.standardCode);
                                $("#measureToolCheckForm").find("input[name=checkUser]").val(_data.checkUserName);
                                $("#measureToolCheckForm").find("input[name=confirmUser]").val(_data.confirmUserName);
                                $("#measureToolCheckForm").find("input[name=measureToolName]").val(_data.measureToolName);
                                $("#measureToolCheckForm").find("input[name=areaName]").val(_data.areaName);
                                $("#measureToolCheckForm").find("input[name=equipName]").val(_data.equipName);
                                $("#measureToolCheckForm").find("input[name=tolerance]").val(_data.tolerance);
                                $("#measureToolCheckForm").find("input[name=standardName]").val(_data.standardName);
                                $("#measureToolCheckForm").find("input[name=temperature]").val(_data.temperature);
                                $("#measureToolCheckForm").find("input[name=checkDate]").val(_data.checkDate);
                                $("#measureToolCheckForm").find("input[name=confirmDate]").val(_data.confirmDate);
                                $("#measureToolCheckForm").find("input[name=standardCert]").val(_data.standardCert);
                                $("#measureToolCheckForm").find("textarea[name=remark]").val(_data.remark);
                                var _itemList = _data.details;
                                var tbody = $("#itemTableTbody");
                                tbody.empty();
                                for (var i = 0; i < _itemList.length; i++) {
                                    //debugger
                                    var tr = $("<tr>" +
                                        "<td>"+_itemList[i].standardValue+"</td>" +
                                        "<td>"+_itemList[i].actualValue+"</td>" +
                                        "<td>"+_itemList[i].deviation+"</td>" +
                                        "<td>"+_itemList[i].checkResult+"</td>" +
                                        "</tr>");
                                    if(_itemList[i].standardValue&&_itemList[i].actualValue&&_itemList[i].deviation&&_itemList[i].checkResult) {
                                        tbody.append(tr);
                                    }
                                }
                                $('#myModal').modal();
                            }
                        } else {
                            DialogUtil.error(response.message);
                        }
                    },
                    error: function () {
                        DialogUtil.error("系统繁忙！");
                    }
                });

            });
        },
        _initMeasureToolCodeQuerySelect2: function () {
            $('#measureToolCodeQuerySelect2').select2({
                ajax: {
                    url: ctx + '/measureTool/measureToolInfo/getMeasureToolList/get.mvc',
                    dataType: 'json',
                    data: function (params) {
                        // Query parameters will be ?search=[term]&page=[page]
                        return {
                            search: params.term,
                            num: params.page || 1,
                            size: 10
                        };
                    },
                    processResults: function (response,params) {
                        // Tranforms the top-level key of the response object from 'items' to 'results'
                        params.page = params.page || 1;
                        var test = [];
                        if (response.rows) {
                            var _data = response.rows;
                            for (var int = 0; int < _data.length; int++) {
                                var obj = {};
                                obj.id = _data[int].pkId;
                                obj.text = _data[int].measureToolCode;
                                test.push(obj);
                            }
                        }
                        return {
                            results: test,
                            pagination :{
                                more:(params.page * 10) < response.total
                            }
                        };
                    },
                    // Additional AJAX parameters go here; see the end of this chapter for the full code of this example
                    cache: false

                },
                placeholder: '请选择',
                language: "zh-CN",
                escapeMarkup: function (markup) {
                    return markup;
                }, // let our custom formatter work
                minimumInputLength: 0
            });
        },
        _modalHidden: function () {
            //模态框消失清空信息
            $("#myModal").on("hide.bs.modal", function () {
                $('#myModal input').each(function () {
                    if ($(this).val() !== "") {
                        $(this).val("");
                    }
                });
                $("textarea").val('');
                //$("#confirmUser").val(null).trigger("change");
                //$("#checkUserWorkNo").val(null).trigger("change");
                $("#itemTableTbody").empty();
                //$('#measureToolCheckForm').bootstrapValidator('resetForm', false);
            });
        }
    }
}();